package com.leetcode.LC_MED;

import java.util.ArrayList;
import java.util.List;

public class LC22_2 {
    public List<String> generateParenthesis(int n) {
        ArrayList<String> list = new ArrayList<>();
        dfs(n, list, new StringBuilder(), 0, 0);
        return list;

    }

    private void dfs(int n, List<String> list, StringBuilder sb, int left, int right) {
        if (sb.length() == n*2) {
            list.add(sb.toString());
            return;
        }

        if (left < n || left == right) {
            dfs(n, list, sb.append('('), left + 1, right);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right < n && left > right) {
            dfs(n, list, sb.append(')'), left, right + 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

    public static void main(String[] args) {
        for (String s : new LC22_2().generateParenthesis(3)) {
            System.out.println(s);
        }
    }
}
